Imports System
Imports System.IO
Imports System.Net
Imports System.Text
Imports System.Security.Cryptography
Imports System.Text.RegularExpressions

Public Class Transfer
    Private Shared ftpPath = "ftp://physcomp1.wlu.ca/ss/"
    Private Shared ftpCred = New NetworkCredential("rusu4904", "d8J01djg")

    Public Shared Function deleteFile(ByVal serverFile As String) As Boolean
        Try

            Dim request As FtpWebRequest = DirectCast(WebRequest.Create(ftpPath & serverFile), FtpWebRequest)
            request.Method = WebRequestMethods.Ftp.DeleteFile
            request.Credentials = ftpCred
            Dim response As WebResponse = request.GetResponse()
            'MsgBox(New StreamReader(response.GetResponseStream).ReadToEnd)
            Return True
        Catch e As Exception
            MsgBox("deleteFile: " & e.Message)
        End Try
        Return False
    End Function

    Public Shared Function uploadFile(ByVal localFile As String, ByVal serverFile As String, Optional ByRef progress As ProgressBar = Nothing) As String
        Try
            Dim request As FtpWebRequest = DirectCast(WebRequest.Create(ftpPath & serverFile), FtpWebRequest)
            request.Method = WebRequestMethods.Ftp.UploadFile
            request.Credentials = ftpCred
            request.UseBinary = True
            Dim ftpStream As IO.Stream = request.GetRequestStream

            'Dim bFile() As Byte = IO.File.ReadAllBytes(localFile)
            'ftpStream.Write(bFile, 0, bFile.Length)

            Dim fIn As New FileStream(localFile, FileMode.Open, FileAccess.Read)
            Dim buffer(4096) As Byte
            Dim bytesDone As Long = 0
            Dim bytesTotal As Long = fIn.Length
            Dim bytesInCur As Integer
            If Not progress Is Nothing Then
                progress.Minimum = 0
                progress.Maximum = 100
            End If
            While bytesDone < bytesTotal
                bytesInCur = fIn.Read(buffer, 0, 4096)
                ftpStream.Write(buffer, 0, bytesInCur)
                bytesDone += CLng(bytesInCur)
                If Not progress Is Nothing Then
                    progress.Value = CInt(bytesDone / bytesTotal * 100)
                    progress.Refresh()
                End If
                Application.DoEvents()
            End While
            progress.Value = 0
            fIn.Close()
            fIn.Dispose()

            ftpStream.Close()
            ftpStream.Dispose()

            Return ftpPath & serverFile
        Catch e As Exception
            MsgBox("uploadFile: " & e.Message)
        End Try
        Return False
    End Function

    Public Shared Function downloadFile(ByVal serverFile As String, ByVal localFile As String, Optional ByVal progress As ProgressBar = Nothing) As Boolean
        Try
            Dim request As FtpWebRequest = DirectCast(WebRequest.Create(ftpPath & serverFile), FtpWebRequest)
            request.Method = WebRequestMethods.Ftp.DownloadFile
            request.Credentials = ftpCred
            request.KeepAlive = False
            request.UseBinary = True
            Dim response As FtpWebResponse = request.GetResponse
            Dim cl As String

            If response.ContentLength > 0 Then
                cl = response.ContentLength
            Else
                'Get filesize from status message
                Dim r As Regex = New Regex("(?<size>\d+[ ]bytes)")
                Dim m As Match = r.Matches(response.StatusDescription)("size")
                cl = m.Value
            End If

            Dim ftpStream As Stream = response.GetResponseStream()
            Dim bufferSize As Integer = 1024
            Dim readCount As Integer
            Dim buffer(bufferSize) As Byte
            Dim tempCount = 0

            Dim fOut As New FileStream(localFile, FileMode.OpenOrCreate)
            If Not progress Is Nothing Then
                progress.Minimum = 0
                progress.Maximum = 100
            End If
            While True
                readCount = ftpStream.Read(buffer, 0, bufferSize)
                If readCount > 0 Then
                    fOut.Write(buffer, 0, readCount)
                    tempCount += readCount
                Else
                    Exit While
                End If
                If Not progress Is Nothing Then
                    progress.Value = CInt(tempCount / cl * 100)
                    progress.Refresh()
                End If
                Application.DoEvents()
            End While
            progress.Value = 0

            ftpStream.Flush()
            fOut.Flush()
            ftpStream.Dispose()
            fOut.Dispose()
            response.Close()

        Catch ui As UriFormatException
            MsgBox("ui " + ui.Message)
        Catch io As IOException
            MsgBox("IO " + io.Message)
        Catch ex As Exception
            MsgBox("EX " + ex.Message)
        End Try
        Return True
    End Function

    Public Shared Function httpDownload(ByVal httpAddress As String, ByVal localFilePath As String) As Boolean
        Try
            Dim request As HttpWebRequest = DirectCast(WebRequest.Create(httpAddress), HttpWebRequest)
            Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
            Dim reader As New StreamReader(response.GetResponseStream())

            Dim fOut As New FileStream(localFilePath, FileMode.OpenOrCreate, FileAccess.Write)

            ' Console application output  
            'Console.WriteLine(reader.ReadToEnd())
            'response.ContentEncoding

            MsgBox(reader.ReadToEnd)

            fOut.Close()
            response.Close()

        Catch e As Exception
            MsgBox("httpDownload: " & e.Message)
        End Try
    End Function
End Class